;Designed for: System V AMD64 ABI
section .text

;Fetch and Add
global sg_fad32
sg_fad32:
    ;returns the *prior* value
    lock xadd [rdi], esi
    mov eax, esi
    ret
global sg_sfad32
sg_sfad32:
    jmp sg_fad32

global sg_fadd32
sg_fadd32:
    ;returns the *adjusted* value
    mov eax, esi
    lock xadd [rdi], esi
    add eax, esi
    ret
global sg_fsadd32
sg_sfadd32:
    jmp sg_fadd32

;Compare and Swap:
global sg_cas16
sg_cas16:
    mov ax, si
    lock cmpxchg [rdi], dx ;t (old val) is in eax
    jz .success
    mov rax, 0x00
    ret
    .success:
    mov rax, 0x01
    ret
global sg_cas32
sg_cas32:
    mov eax, esi
    lock cmpxchg [rdi], edx ;t (old val) is in eax
    jz .success
    mov rax, 0x00
    ret
    .success:
    mov rax, 0x01
    ret
global sg_scas32
sg_scas32:
    mov eax, esi
    lock cmpxchg [rdi], edx ;t (old val) is in eax
    jz .success
    mov rax, 0x00
    ret
    .success:
    mov rax, 0x01
    ret

global sg_cas64
sg_cas64:
    mov rax, rsi
    lock cmpxchg [rdi], rdx ;only compares against ax/eax/rax according to AMD
    jz .success
    mov rax, 0x00
    ret
    .success:
    mov rax, 0x01
    ret